package network.themis.rms.console.service;

import lombok.extern.slf4j.Slf4j;
import network.themis.rms.console.common.model.FileVO;
import network.themis.rms.console.common.model.RestResp;
import network.themis.rms.console.entity.biz.*;
import network.themis.rms.console.repo.biz.BannerTipRepo;
import network.themis.rms.console.repo.biz.ContactRepo;
import network.themis.rms.console.repo.biz.NewsTipRepo;
import org.hibernate.jpa.internal.ExceptionMapperLegacyJpaImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author ccl
 * @time 2018-07-20 13:46
 * @name NewsService
 * @desc:
 */
@Slf4j
@Service
public class NewsService {
    @Resource
    private NewsTipRepo newsTipRepo;

    @Resource
    private BannerTipRepo bannerTipRepo;

    @Resource
    private ContactRepo contactRepo;

    @Resource
    private UploadService uploadService;

    public RestResp info(){
        return RestResp.success("success","welcome to visit themis");
    }

    public RestResp saveNewsTip(NewsTipVO vo){
        try{
            NewsTip newsTip = newsTipRepo.save(vo);
            return RestResp.success("保存成功",newsTip);
        }catch (Exception e){
            log.error("", e);
            return RestResp.fail();
        }
    }

    public RestResp removeNewsTip(Long id){
        try{
            newsTipRepo.deleteById(id);
            return RestResp.success("删除成功", null);
        }catch (Exception e){
            log.error("", e);
            return RestResp.fail();
        }
    }

    public RestResp addBannerTip(FileVO vo){
        try{
            String fileName = uploadService.upload(vo, false);
            if(null == fileName){
                return RestResp.fail("保存失败");
            }
            BannerTip bannerTip = new BannerTip();
            bannerTip.setImage(fileName);
            bannerTip.setCreateTime(System.currentTimeMillis());
            bannerTip = bannerTipRepo.save(bannerTip);
            return RestResp.success("保存成功",bannerTip);
        }catch (Exception e){
            log.error("", e);
            return RestResp.fail();
        }
    }

    public RestResp removeBannerTip(Long id){
        try{
            bannerTipRepo.deleteById(id);
            return RestResp.success("删除成功", null);
        }catch (Exception e){
            log.error("", e);
            return RestResp.fail();
        }
    }

    public RestResp getNewsTip(){
        List<NewsTip> newsTipList = newsTipRepo.findByEnabled(1);
        return RestResp.success(newsTipList);
    }


    public RestResp getBannerTip(){
        List<BannerTip> bannerTipList = bannerTipRepo.findByEnabled(1);
        return RestResp.success(bannerTipList);
    }

    public RestResp getContactInfo(String code){
        Contact product = contactRepo.findByCode(code);
        return RestResp.success(product);
    }
}
